package com.hhf.feiojjudgeservice.job.once;

import com.hhf.feiojcommonservice.constant.RabbitMQConstant;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @Author hhf
 * @Date 2024/11/4
 * @Description
 */
@Slf4j
@Component
public class InitRabbitMQ {

    @Value("${spring.rabbitmq.host:localhost}")
    private String host;

    @PostConstruct
    public  void init(){
        log.info("start init rabbitMQ");
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(host);
        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {

            //创建exchange
            channel.exchangeDeclare(RabbitMQConstant.EXCHANGE_NAME,"direct");

            //创建queue
            channel.queueDeclare(RabbitMQConstant.QUEUE_NAME,true,false,false,null);


            //绑定 queue 与 exchange
            channel.queueBind(RabbitMQConstant.QUEUE_NAME,RabbitMQConstant.EXCHANGE_NAME,RabbitMQConstant.ROUTING_KEY);
            log.info("rabbitMQ init success");

        }catch (Exception e){
            log.error("rabbitMQ init fail:{}",e.getMessage());
        }
    }


}
